﻿using BrnMall.Core;
using BrnMall.Manager.Manager.WebIM;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using BrnMall.Manager.Domain.WebIM;
using BrnMall.Sdk.WeiXin.Tool;

namespace QIDong.WeApp.Util
{
    public class WebIMUtil
    {
        public const uint sdkappid = 1400101388;
        public const uint accountType = 29625;
        // 下面的公私钥路径都是绝对路径，请开发者自行修改

        public static string GenSig(string identifier)
        {
            // 生成 sig 文件
            FileStream f = new FileStream(ConfigurationManager.AppSettings["webim_pri_key_path"], FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(f);
            byte[] b = new byte[f.Length];
            reader.Read(b, 0, b.Length);
            string pri_key = Encoding.Default.GetString(b);

            StringBuilder sig = new StringBuilder(4096);
            StringBuilder err_msg = new StringBuilder(4096);
            int ret = sigcheck.tls_gen_sig_ex(
                sdkappid,
                identifier,
                sig,
                4096,
                pri_key,
                (UInt32)pri_key.Length,
                err_msg,
                4096);
            if (0 != ret)
            {
                throw new Exception(err_msg.ToString());
            }
            return sig.ToString();
        }

        public static string GetUserSig(int uid)
        {
            string userSigString = null;
            var userSig = UserSigManager.GetUserSig(uid);

            if (userSig != null)
            {
                if ((DateTime.Now - userSig.CreateTime).Days > 180)
                {
                    UserSigManager.DeleteUserSig(uid);
                }
                else
                {
                    userSigString = userSig.Sig;
                }
            }
            if (string.IsNullOrEmpty(userSigString))
            {
                userSigString = WebIMUtil.GenSig(uid.ToString());
                UserSigManager.AddUserSig(new UserSig { uid = uid, CreateTime = DateTime.Now, Sig = userSigString });
            }
            return userSigString;
        }

        /// <summary>
        /// 导入用户
        /// </summary>
        /// <param name="user"></param>
        public static void ImportUser(PartUserInfo user)
        {
            var userSigString = GetUserSig(1);
            if (string.IsNullOrEmpty(userSigString)) return;
            var url =
                $"https://console.tim.qq.com/v4/im_open_login_svc/account_import?usersig={userSigString}&identifier=1&sdkappid={sdkappid}&random={Guid.NewGuid():N}&contenttype=json";
            var bodyData =
                $"{{\"Identifier\":\"{user.Uid}\",\"Nick\":\"{user.NickName}\",\"FaceUrl\":\"{user.Avatar}\"}}";
            RestHttp.Post(url, bodyData);
           
        }
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user"></param>
        public static void UpdateUser(PartUserInfo user)
        {
            var userSigString = GetUserSig(1);
            if (string.IsNullOrEmpty(userSigString)) return;
            var url =
                $"https://console.tim.qq.com/v4/profile/portrait_set?usersig={userSigString}&identifier=1&sdkappid={sdkappid}&random={Guid.NewGuid():N}&contenttype=json";
            var bodyData = $"{{\"From_Account\":\"{user.Uid}\",\"ProfileItem\":[{{\"Tag\":\"Tag_Profile_IM_Nick\",\"Value\":\"{user.NickName}\"}},{{\"Tag\":\"Tag_Profile_IM_Image\",\"Value\":\"{user.Avatar}\"}}]}}";

            RestHttp.Post(url, bodyData);
        }
        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="friendUid"></param>
        public static void AddFriend(int uid, int friendUid)
        {
            var userSigString = GetUserSig(1);
            if (string.IsNullOrEmpty(userSigString)) return;
            var url = $"https://console.tim.qq.com/v4/sns/friend_add?usersig={userSigString}&identifier=1&sdkappid={sdkappid}&random={Guid.NewGuid():N}&contenttype=json";
            var bodyData =
                $"{{\"From_Account\":\"{uid}\",\"AddFriendItem\":[{{\"To_Account\":\"{friendUid}\",\"Remark\":\"管理员添加\",\"AddSource\":\"AddSource_Type_WeApp\"}}],\"AddType\":\"Add_Type_Both\",\"ForceAddFlags\":1}}";
            RestHttp.Post(url, bodyData);
        }
    }
    internal class dllpath
    {
        // 开发者调用 dll 时请注意项目的平台属性，下面的路径是 demo 创建时使用的，请自己使用予以修改
        // 请使用适当的平台 dll
        //public const string DllPath = @"D:\src\oicq64\tinyid\tls_sig_api\windows\64\lib\libsigcheck\sigcheck.dll";       // 64 位
        // 如果选择 Any CPU 平台，默认加载 32 位 dll

        public const string DllPath = @"C:\weapp.711688.net.cn\WebIM\sigcheck.dll";     // 32 位


    }

    internal class sigcheck
    {
        [DllImport(dllpath.DllPath, EntryPoint = "tls_gen_sig", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public extern static int tls_gen_sig(
            UInt32 expire,
            string appid3rd,
            UInt32 sdkappid,
            string identifier,
            UInt32 acctype,
            StringBuilder sig,
            UInt32 sig_buff_len,
            string pri_key,
            UInt32 pri_key_len,
            StringBuilder err_msg,
            UInt32 err_msg_buff_len
        );

        [DllImport(dllpath.DllPath, EntryPoint = "tls_vri_sig", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public extern static int tls_vri_sig(
            string sig,
            string pub_key,
            UInt32 pub_key_len,
            UInt32 acctype,
            string appid3rd,
            UInt32 sdkappid,
            string identifier,
            StringBuilder err_msg,
            UInt32 err_msg_buff_len
        );

        [DllImport(dllpath.DllPath, EntryPoint = "tls_gen_sig_ex", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public extern static int tls_gen_sig_ex(
            UInt32 sdkappid,
            string identifier,
            StringBuilder sig,
            UInt32 sig_buff_len,
            string pri_key,
            UInt32 pri_key_len,
            StringBuilder err_msg,
            UInt32 err_msg_buff_len
        );

        [DllImport(dllpath.DllPath, EntryPoint = "tls_vri_sig_ex", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public extern static int tls_vri_sig_ex(
            string sig,
            string pub_key,
            UInt32 pub_key_len,
            UInt32 sdkappid,
            string identifier,
            ref UInt32 expire_time,
            ref UInt32 init_time,
            StringBuilder err_msg,
            UInt32 err_msg_buff_len
        );
    }


}